package gameObjects;

import java.io.IOException;
import editor.Grid;
import gameObjects.Bike.POINTTO;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import logic.Coords2D;
import logic.AttackPlayer;
import logic.TurnController;

public class BikeCOM{

	public enum TURNDIRECTION{LEFT,RIGHT,AWAY};
	private TurnController tc = new TurnController();
	private Bike    bike;
	//
	private AttackPlayer    attackPlayer;
	private boolean 		followHuman;
	
	public BikeCOM(String name,int color, boolean isHuman,Node scene,int speed) throws IOException {
		
		Coords2D sp = Grid.startPoints.firstElement();
					  Grid.startPoints.remove(0);
		POINTTO    p  = POINTTO.NORTH;
		if (sp.getY()>63) p = POINTTO.SOUTH;
		if (sp.getY()<64) p = POINTTO.NORTH;
		bike = new Bike(name, sp, p, color, isHuman,scene,speed);
		//
		this.attackPlayer=new AttackPlayer();
		this.followHuman=false;
	}
	
	public Node getModel3D()
	{
		return bike;
	}
	
	public boolean isAlive()
	{
		return this.bike.isAlive; 
	}
	
	public POINTTO getCurrentPoint()
	{
		return bike.getCurrentDirection();
	}
	
	private void updateDirection(TURNDIRECTION direction, float tpf)
	{
		if (direction==TURNDIRECTION.RIGHT) {bike.turnRight(tpf);}
		if (direction==TURNDIRECTION.LEFT)  {bike.turnLeft(tpf);}
		bike.goForward(tpf);
	}
	
	public boolean updateMovement(float tpf)
	{	
		
		TURNDIRECTION direction = null;
		if (bike.isAlive())
		{
			if( (bike.getPosX()>1 && bike.getPosX()<127)
				&&
			    (bike.getPosZ()>1 && bike.getPosZ()<127))
			{
				this.followHuman=false;
				//parte per seguire il coso
				this.attackPlayer.set(bike.getPosX(),bike.getPosZ(),bike.getCurrentDirection());
				if(this.attackPlayer.isNear())
				{
					System.out.println("E NEAR");
					this.followHuman=true;
					direction=this.attackPlayer.attack();
					if (direction==TURNDIRECTION.RIGHT) {bike.turnRight(tpf);}
					if (direction==TURNDIRECTION.LEFT)  {bike.turnLeft(tpf);}
				}
				direction =tc.chooseDirection(bike.getCurrentDirection(),bike.getPosX(),bike.getPosZ(),bike.getShield(),followHuman); 
				updateDirection(direction, tpf);
				bike.setCubeUpdate(tpf);
			}
			else
				bike.isAlive=false;
		}
		else
		{
			bike.setLocalTranslation(new Vector3f(-10000,-10000,-10000));
			bike.clearCubes(tpf);
			bike.pause();
		}
		
		return false;
	}
	
	public void sfxStop()
	{
		bike.sfxStop();
	}
	
	public Bike getBike()
	{
		return bike;
	}
}
